﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.rtda
{
    class JvmStack
    {
        public uint maxSize;
        public uint size;
        public JFrame _top;

        public JvmStack(uint maxSize)
        {
            this.maxSize = maxSize;
        }

        public void Push(JFrame frame)
        {
            if (size >= maxSize)
            {
                Console.WriteLine("java.lang.StackOverflowError");
                Environment.Exit(0);
            }
            if (_top != null)
            {
                frame.next = _top;
            }
            _top = frame;
            size++;
        }

        public JFrame Pop()
        {
            if (_top == null)
            {
                Console.WriteLine("jvm stack is empty!");
                Environment.Exit(0);
            }
            JFrame frame = _top;
            _top = _top.next;
            frame.next = null;
            size--;
            return frame;
        }

        public JFrame Top()
        {
            if (_top == null)
            {
                Console.WriteLine("jvm stack is empty!");
                Environment.Exit(0);
            }
            return _top;
        }

        bool IsEmpty()
        {
            return _top == null;
        }

        public void Clear()
        {
            while (!IsEmpty())
            {
                Pop();
            }
        }

        public JFrame[] GetFrames(int skip)
        {
            if (skip >= size)
            {
                return new JFrame[0];
            }
            JFrame[] frames = new JFrame[size - skip];
            int index = 0;
            for (JFrame f = _top; f != null; f = f.next, index++)
            {
                if (index >= skip)
                {
                    frames[index - skip] = f;
                }
            }
            return frames;
        }
    }
}
